﻿using Infrastructure.DbUtility;
using Infrastructure.Utility;
using System;
using System.Collections.Generic;
using System.Data;
using System.Web.Script.Serialization;
public partial class admin_chapter : BasePage
{
    protected int subjectId
    {
        get { return ViewState["subjectId"] == null ? 0 : (int)ViewState["subjectId"]; }
        set { ViewState["subjectId"] = value; }
    }
    protected string subjectName
    {
        get { return Convert.ToString(ViewState["subjectName"]); }
        set { ViewState["subjectName"] = value; }
    }

    protected int gradeSubjectId
    {
        get { return ViewState["gradeSubjectId"] == null ? 0 : (int)ViewState["gradeSubjectId"]; }
        set { ViewState["gradeSubjectId"] = value; }
    }

    protected void Page_Load(object sender, EventArgs e)
    {


        string ssid = Request["sid"];
        int sid = 0;
        if (!IsPostBack)
        {
            if (int.TryParse(ssid, out sid) && sid > 0) this.InitSubjectInfo(sid);
        }

        if (Request["data"] == "tree") this.LoadChapterTree(Request["sid"]);

        if (Request["do"] == "save") this.SaveChapter();
        else if (Request["do"] == "del") this.DelChapter();
    }

    private void DelChapter()
    {
        int cid = 0;
        var part = Request["part"];
        int.TryParse(Request["cid"], out cid);

        string sql = "DELETE FROM Chapter WHERE [cid] = {0} OR [part] LIKE {1} + '%'";

        DbHelper db = new DbHelper();
        db.ExecuteUpdateEx(sql, cid, part);

        this.LoadChapterTree(subjectId.ToString());
    }

    private void SaveChapter()
    {
        var gsid = gradeSubjectId;
        var sid = subjectId;
        var subjectname = subjectName;
        var part = Request["part"];
        var title = Request["title"];
        var content = string.Empty;
        var description = string.Empty;
        var creator = 1;

        string sql = "INSERT INTO Chapter ([gsid],[sid],[subjectname],[gid],[gname],[part],[title],[content],[description],[creator],[status]) "
                       + "SELECT {0},{1},{2},B.nid,B.name,{3},{4},{5},{6},{7},1 from GradeSubject A (NOLOCK) LEFT JOIN Grade B (NOLOCK) ON A.gid = B.nid WHERE A.gsid = {0}";

        DbHelper db = new DbHelper();
        db.ExecuteUpdateEx(sql, gsid, sid, subjectname, part, title, content, description, creator);

        this.LoadChapterTree(sid.ToString());
    }

    private void LoadChapterTree(string ssid)
    {
        int sid = 0;
        if (!int.TryParse(ssid, out  sid) && sid <= 0) return;

        string sql = "SELECT * FROM Chapter (NOLOCK) WHERE sid = " + sid;
        DbHelper db = new DbHelper();
        var table = db.ExecQuery(sql);

        if (table == null || table.Rows.Count == 0) table = new DataTable();

        List<object> lstRoot = new List<object>();

        foreach (DataRow row in table.Rows)
        {
            var part = row.Value("part");
            if (part.IndexOf(".") > 0) continue;
            List<object> lstChildren = new List<object>();
            lstRoot.Add(new { text = "[" + part + "] " + row.Value("title"), href = "chapter.edit.aspx?cid=" + row.Value<int>("cid"), part = part, tags = new string[1] { row.Value("cid") }, nodes = this.FindChildrens(table, row.Value<int>("cid"), part, lstChildren) });
        }

        if (lstRoot.Count == 0) lstRoot.Add(new { text = "<无>", href = "javascript:void(0)" });

        JavaScriptSerializer jsSerializer = new JavaScriptSerializer();
        Response.Clear();
        Response.Write(jsSerializer.Serialize(new { success = true, data = lstRoot.ToArray() }));
        Response.End();
    }

    private object FindChildrens(DataTable table, int cid, string part, List<object> lstChildren)
    {
        //递归获取章节目录结构。
        var childrenRows = table.Select("part like '" + part + "%' AND part <> '" + part + "'");

        foreach (DataRow row in childrenRows)
        {
            var childrenPart = row.Value("part");
            int childrenId = row.Value<int>("cid");

            if (childrenPart.LastIndexOf(".") != part.Length) continue;//过滤掉子级的下一级。

            List<object> lstSub = new List<object>();
            lstChildren.Add(new { text = "[" + childrenPart + "] " + row.Value("title"), href = "chapter.edit.aspx?cid=" + childrenId, part = childrenPart, tags = new string[1] { row.Value("cid") }, nodes = this.FindChildrens(table, childrenId, childrenPart, lstSub) });
        }

        if (lstChildren.Count == 0) return false;
        return lstChildren.ToArray();
    }

    private void InitSubjectInfo(int sid)
    {
        string sql = "SELECT sid,[name] FROM Subject (NOLOCK) WHERE sid = " + sid;

        DbHelper db = new DbHelper();
        var table = db.ExecQuery(sql);

        if (table == null || table.Rows.Count == 0) return;

        subjectId = (int)table.Rows[0]["sid"];
        subjectName = Convert.ToString(table.Rows[0]["name"]);
        var gsid = 0;
        int.TryParse(Request["gsid"], out  gsid);
        gradeSubjectId = gsid;
    }

}